package main

import (
	"fmt"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

type LoginForm struct {
	User     string `json:"user" form:"user" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
}

type LoginForm1 struct {
	User      string `json:"user" form:"user" binding:"required"`
	Password1 string `json:"password1" form:"password1" binding:"required"`
}

func main() {
	gin.ForceConsoleColor()
	r := gin.Default()
	r.Use(Logger())
	r.POST("/login", Login)
	r.GET("/getb", getDataB)
	r.GET("/getc", GetDataC)
	r.GET("/getd", GetDataD)
	// 监听并在 0.0.0.0:8080 上启动服务
	r.Run(":8080")
}
func GetDataD(c *gin.Context) {
	var b StructD
	c.Bind(&b)
	fmt.Printf("GetDataC__%+v \n", b)
	c.JSON(200, gin.H{
		"x": b.NestedAnonyStruct,
		"d": b.FieldD,
	})
}
func GetDataC(c *gin.Context) {
	var b StructC
	c.Bind(&b)
	fmt.Printf("GetDataC__%+v \n", b)
	c.JSON(200, gin.H{
		"a": b.NestedStructPointer,
		"c": b.FieldC,
	})
}

func getDataB(c *gin.Context) {
	var b StructB
	c.Bind(&b)
	fmt.Printf("__%+v \n", b)
	c.JSON(200, gin.H{
		"a": b.NestedStruct,
		"b": b.FieldB,
	})
}

func Login(c *gin.Context) {
	form := &LoginForm{}
	//err := c.ShouldBindWith(&form, binding.Query)
	err := c.ShouldBind(form)
	fmt.Println("form", form)
	if err != nil {
		c.JSON(200, gin.H{"status": err.Error()})
		return
	}

	ids := c.QueryArray("ids[]")
	fmt.Printf("ids --------%+v \n", ids)

	contnet := c.PostFormArray("contnet[]")
	fmt.Printf("contnet --------%+v \n", contnet)

	if form.User == "user" && form.Password == "password" {
		c.JSON(200, form)
	} else {
		c.JSON(401, gin.H{"status": "unauthorized"})
	}
}

type StructA struct {
	FieldA string `form:"field_a" json:"fieldA"`
}

type StructB struct {
	NestedStruct StructA
	FieldB       string `form:"field_b" json:"fieldB"`
}
type StructC struct {
	NestedStructPointer *StructA
	FieldC              string `form:"field_c"`
}

type StructD struct {
	NestedAnonyStruct struct {
		FieldX string `form:"field_x"`
	}
	FieldD string `form:"field_d"`
}

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()
		fmt.Println("111111111111111")
		// 设置 example 变量
		c.Set("example", "12345")

		// 请求前

		c.Next()
		fmt.Println("2222222222222")
		// 请求后
		latency := time.Since(t)
		log.Print(latency)

		// 获取发送的 status
		status := c.Writer.Status()
		log.Println(status)
	}
}
